﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GameTimeSystem
{
    public class GameTimer : IGameTimer
    {
        public bool IsActive { get; set; }

        public float EdgeTime { get; set; }

        public bool IsStatic;

        private float currentTime;

        private Func<bool> CheckEnd;
        private Action OnCompleted;
        private Action<float> OnUpdate;
        private List<GameTimer> ownerList;
        private ObjPool<GameTimer> ownerPool;

        public void Init()
        {

        }

        public void SetOwner(List<GameTimer> ownerList,ObjPool<GameTimer> ownerPool)
        {
            this.ownerList = ownerList;
            this.ownerPool = ownerPool;
        }

        public void Dispose()
        {
            
        }

        public void Register(Func<bool> checkEnd = null,Action < float> onUpdate=null, Action onComplete = null )
        {
            OnUpdate = onUpdate;
            CheckEnd = checkEnd;
            OnCompleted = onComplete;
        }

        public void Register(float edgeTime,  Action<float> onUpdate = null, Action onComplete = null )
        {
            Register(null,onUpdate, onComplete);
            EdgeTime = edgeTime;
        }

        public void Register(Action<float> onUpdate)
        {
            Register(null, onUpdate, null);
            EdgeTime = -1;
        }

        public void Polling(float deltaTime)
        {
            if (OnUpdate!=null)
            {
                OnUpdate(deltaTime);
            }
            bool isEnd=false;
            if (CheckEnd != null)
            {
                isEnd = CheckEnd();
            }
            else if(EdgeTime!=-1)
            {
                currentTime += deltaTime;
                if (currentTime>=EdgeTime)
                {
                    isEnd = true;
                }
                //按照时间来走
            }
            if (isEnd)
            {
                if (!IsStatic)
                {
                    ownerPool.RemoveObjToPool(this);
                }
                
                if (OnCompleted!=null)
                {
                    OnCompleted();
                }
            }
        }

        public void OnEnable()
        {

        }

        public void OnDisable()
        {
            ownerList.Remove(this);
        }
    }
}
